package com.feizhoutuobang.shapeline.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

public class WebClient {
	private static final Logger LOG = Logger.getLogger(WebClient.class);
	
	private int timeout = 120000;
	private boolean useProxy = false;
	private String proxyHost;
	private int proxyPort;
	private HttpClient httpClient = null;
	private GetMethod get = null;
	
	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeoutInMilliseconds) {
		this.timeout = timeoutInMilliseconds;
	}

	public boolean isUseProxy() {
		return useProxy;
	}

	public void setUseProxy(boolean useProxy) {
		this.useProxy = useProxy;
	}
	
	public String getProxyHost() {
		return proxyHost;
	}
	
	public void setProxyHost(String proxyHost) {
		this.proxyHost = proxyHost;
	}
	
	public int getProxyPort() {
		return proxyPort;
	}
	
	public void setProxyPort(int proxyPort) {
		this.proxyPort = proxyPort;
	}
	
	public InputStream downloadAsStream(String url) {
		initHttpClient();
		get = new GetMethod(url);
		try {
			httpClient.executeMethod(get);
			return get.getResponseBodyAsStream();
		} catch (HttpException e) {
			LOG.error("error when download url: " + url, e);
		} catch (IOException e) {
			LOG.error("error when download url: " + url, e);
		}
		return null;
	}

	private void initHttpClient() {
		if (httpClient == null) {
			httpClient = new HttpClient();
			httpClient.getParams().setConnectionManagerTimeout(timeout);
		}
	}

	public void release() {
		try {
			get.releaseConnection(); 
		} 
		catch (Exception e) {
			LOG.error("error when release http connection", e);
		}
		get = null;
	}
	
}
